package com.qianshui.co.medical.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qianshui.co.medical.db.DaoFactory;
import com.qianshui.co.medical.db.User;

public class SMSCommon {

	static Map<String, String> pair_map = new HashMap<String, String>();

	public static String SendSMSMEssage(String Phone) {
		String returnstatus;
		if (ValidateMobile(Phone))// 验证孕妇的手机号码是否合法
		{
			returnstatus = SendMessage(Phone);

		} else {
			returnstatus = "手机号码不存在";
		}

		return returnstatus;

	}

	public static String SendSMSPassMessage(String Phone) {
		String returnstatus;
		if (ValidateMobile(Phone)&&IsExist(Phone))// 验证孕妇的手机号码是否合法
		{
			returnstatus = SendPasswordMessage(Phone);

		} else {
			returnstatus = "无效手机号码";
		}

		return returnstatus;

	}

	public static boolean ValidateCode(String phone, String code) {
		if (pair_map.containsKey(phone)) {
			if (pair_map.get(phone).contentEquals(code)) {
				pair_map.remove(phone);
				return true;
			}
		}
		return false;
	}
	
	

	private static String SendMessage(String phone) {
		// TODO Auto-generated method stub

		String code = String.valueOf(GetCode());
		String message = "您的验证码：" + code + "（注册验证码，五分钟内有效，如非本人操作请忽略）";// 验证码程序随机生成6位数字，组成到一个字符串.
		String Url = "http://web.cr6868.com/asmx/smsservice.aspx";

		String PostDate = "name=18620185541&pwd=6627F7D500103E105E2A576B2E22&content="
				+ message + "&mobile=" + phone + "&sign=重庆妇幼&type=pt";// 签名
		String res = sendPost(Url, PostDate);
		String status = res.substring(0, 1);
		if (status.equals("0")) {
			pair_map.put(phone, code);
		}
		return getMessageStatus(status);
	}

	private static String SendPasswordMessage(String phone) {
		// TODO Auto-generated method stub

		String code = String.valueOf(GetCode());
		String message = "你的新密码是:" + code + "登陆后请及时修改密码.";// 验证码程序随机生成6位数字，组成到一个字符串.
		String Url = "http://web.cr6868.com/asmx/smsservice.aspx";

		String PostDate = "name=18620185541&pwd=6627F7D500103E105E2A576B2E22&content="
				+ message + "&mobile=" + phone + "&sign=重庆妇幼&type=pt";// 签名
		String res = sendPost(Url, PostDate);
		String status = res.substring(0, 1);
		if (status.equals("0")) {
			List<User> u = DaoFactory.getInstance().getUser_dao()
					.findByProperty("phone", phone);
			if (u.size() != 0) {

				u.get(0).setPassword(MD5Util.MD5(code));
				DaoFactory.getInstance().getUser_dao().saveOrUpdate(u.get(0));
			}
		}
		return getMessageStatus(status);
	}

	private static int GetCode() {
		int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = array[index];
			array[index] = array[i - 1];
			array[i - 1] = tmp;
		}
		int result = 0;
		for (int i = 0; i < 6; i++)
			result = result * 10 + array[i];

		return result;
	}

	private static String getMessageStatus(String status) {

		String returnstatus = "";
		if (status.equals("0")) {
			returnstatus = "success";
		} else if (status.equals("1")) {
			returnstatus = "含有敏感词汇";
		} else if (status.equals("2")) {
			returnstatus = "余额不足";
		} else if (status.equals("3")) {
			returnstatus = "没有号码";
		} else if (status.equals("14")) {
			returnstatus = "格式错误";
		} else if (status.equals("-1")) {
			returnstatus = "系统异常";
		}
		return returnstatus;
	}

	private static boolean ValidateMobile(String mobile) {

		if (mobile == null || mobile.equals("")) {
			return false;
		}
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

		Matcher m = p.matcher(mobile);
		return m.matches();

	}
	
	private static boolean IsExist(String mobile) {

		List<User> u = DaoFactory.getInstance().getUser_dao()
				.findByProperty("phone", mobile);
		if (u.size() > 0) {
			return true;
		}
		return false;
	}

	private static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {

			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("charsert", "UTF-8");
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(
					conn.getOutputStream(), "UTF-8"));
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}
